from django.shortcuts import render
from django.views.generic.base import View
from django.http import JsonResponse

from apps.operations.models import UserFavorites, CourseComments
from apps.operations.forms import UserFavForm, CommentsForm
from apps.courses.models import Course, CourseTag
from apps.organizations.models import CourseOrg, Teacher


class Index(View):
    def get(self, request, *args, **kwargs):
        courses = Course.objects.order_by("-students")[:8]
        course_orgs = CourseOrg.objects.order_by("-students")[:8]
        teachers = Teacher.objects.order_by("-fav_nums")[:8]
        return render(request, "index.html", {
            "courses": courses,
            "course_orgs": course_orgs,
            "teachers": teachers,
        })


# 用户收藏功能
class AddFavView(View):
    def post(self, request, *args, **kwargs):
        # 先判断用户是否登录
        if not request.user.is_authenticated:
            return JsonResponse({
                "status": "fail",
                "msg": "用户未登录"
            })
        # 获取提交的数据
        user_fav_form = UserFavForm(request.POST)
        # 判断用户传参是否正确
        if user_fav_form.is_valid():
            fav_id = user_fav_form.cleaned_data["fav_id"]
            fav_type = user_fav_form.cleaned_data["fav_type"]

            existed_records = UserFavorites.objects.filter(user=request.user, fav_id=fav_id, fav_type=fav_type)
            # 是否已经收藏
            if existed_records:
                # 已收藏就进行取消收藏
                existed_records.delete()
                # 判断收藏对象的类型
                # 课程
                if fav_type == 1:
                    course = Course.objects.get(id=fav_id)
                    course.fav_nums -= 1
                    course.save()
                # 机构
                elif fav_type == 2:
                    course_org = CourseOrg.objects.get(id=fav_id)
                    course_org.fav_nums -= 1
                    course_org.save()
                # 教师
                elif fav_type == 3:
                    teacher = Teacher.objects.get(id=fav_id)
                    teacher.fav_nums -= 1
                    teacher.save()

                return JsonResponse({
                    "status": "success",
                    "msg": "已取消收藏"
                })
            else:
                # 未收藏进行收藏
                user_fav = UserFavorites()
                user_fav.fav_id = fav_id
                user_fav.fav_type = fav_type
                user_fav.user = request.user
                user_fav.save()

                # 判断收藏对象的类型
                # 课程
                if fav_type == 1:
                    course = Course.objects.get(id=fav_id)
                    course.fav_nums += 1
                    course.save()
                # 机构
                elif fav_type == 2:
                    course_org = CourseOrg.objects.get(id=fav_id)
                    course_org.fav_nums += 1
                    course_org.save()
                # 教师
                elif fav_type == 3:
                    teacher = Teacher.objects.get(id=fav_id)
                    teacher.fav_nums += 1
                    teacher.save()

                return JsonResponse({
                    "status": "success",
                    "msg": "已收藏"
                })
        # 用户传参不正确
        else:
            return JsonResponse({
                "status": "fail",
                "msg": "参数错误"
            })


# 课程评论
class CommentView(View):
    def post(self, request, *args, **kwargs):
        # 先判断用户是否登录
        if not request.user.is_authenticated:
            return JsonResponse({
                "status": "fail",
                "msg": "用户未登录"
            })
        # 获取提交的数据
        user_comment_form = CommentsForm(request.POST)
        # 判断用户传参是否正确
        if user_comment_form.is_valid():
            course = user_comment_form.cleaned_data["course"]
            comments = user_comment_form.cleaned_data["comments"]
            comment = CourseComments()

            comment.user = request.user
            comment.comments = comments

            comment.course = course
            comment.save()

            return JsonResponse({
                "status": "success",
            })

        # 用户传参不正确
        else:
            return JsonResponse({
                "status": "fail",
                "msg": "参数错误"
            })


# 课程搜索
class SearchView(View):
    def post(self, request, *args, **kwargs):
        # 获取提交的数据
        course_tag = request.GET.get("search_input", "")
        # 判断用户传参是否正确
        if course_tag is not None:
            search_courses = CourseTag.objects.filter(tag=course_tag)
            course_inter = set()
            for course_tag in search_courses:
                course_inter.add(course_tag.course)

            return render(request, 'search.html', {
                "search_courses": search_courses,
                "course_inter": course_inter,
                "msg": "搜索成功"
            })

        # 用户传参不正确
        else:
            return render(request, 'search.html', {
                "msg": "抱歉！搜索不到该课程，您可以尝试搜索其他课程。",
            })
